package com.emmmya.ocs.modules.system.controller;

import com.emmmya.ocs.modules.system.annotation.OperateLog;
import com.emmmya.ocs.common.entity.IntermediateEntity;
import com.emmmya.ocs.common.entity.LayUITree;
import com.emmmya.ocs.common.utils.ResultUtil;
import com.emmmya.ocs.common.vo.Result;
import com.emmmya.ocs.modules.system.entity.Permissions;
import com.emmmya.ocs.modules.system.entity.Role;
import com.emmmya.ocs.modules.system.service.PermissionsService;
import com.emmmya.ocs.modules.system.service.RoleService;
import com.emmmya.ocs.modules.system.utils.LayuiTreeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 创建人：咕噜肉IT小店-黑医
 * 创建时间 2022年08月11日 16:07:20
 * 描述：
 */
@RestController
@RequestMapping("permission")
@Slf4j
public class PermissionController {

    @Autowired
    RoleService roleService;

    @Autowired
    PermissionsService permissionsService;

    @Autowired
    LayuiTreeUtils layuiTreeUtils;

    @GetMapping("getPermissionLayuiTree")
    public Result<Object> getAllPermission(){
        List<Permissions> permissionsList = permissionsService.findByLevel(1);
        List<LayUITree> layUITrees = layuiTreeUtils.changePermissionTree(permissionsList, false, false);
        return ResultUtil.data(layUITrees);
    }

    /**
     * 根据id查询权限数据
     */
    @GetMapping("getPermissionById")
    public Result<Object> getPermissionById(@RequestParam("id")Long id){
        Permissions permissions = permissionsService.get(id);
        return ResultUtil.data(permissions);
    }


    @RequestMapping("addPermission")
    @OperateLog(value="添加权限",module = "权限管理模块")
    public Result<Object> addPermission(@RequestBody Permissions per){
        try {
            per.setId(null);
            Long parentId = per.getParentId();
            if(parentId == null || parentId == -1){
                per.setLevel(1);
            }else{
                Permissions parentPer = permissionsService.get(parentId);
                if(parentPer == null){
                    return ResultUtil.error("绑定的父权限不存在，请确认后再");
                }
                per.setLevel(parentPer.getLevel() + 1);
            }
            Permissions save = permissionsService.save(per);
            return ResultUtil.data(save,"添加成功",200);
        } catch (Exception e) {
//            e.printStackTrace();
            log.warn("【权限管理】新增权限时出现错误，错误信息："+ e.getMessage());
            return ResultUtil.error("系统错误，错误信息："+ e.getMessage());
        }
    }

    @RequestMapping(value = "updatePermissionById")
    @OperateLog(value = "根据id更新权限",module = "权限模块")
    public Result<Object> updatePermissionById(@RequestBody Permissions per){
        try {
            Long parentId = per.getParentId();
            if(parentId == null || parentId == -1){
                per.setLevel(1);
            }else{
                Permissions parentPer = permissionsService.get(parentId);
                if(parentPer == null){
                    return ResultUtil.error("绑定的父权限不存在，请确认后再");
                }
                per.setLevel(parentPer.getLevel() + 1);
            }
            Permissions update = permissionsService.update(per);
            return ResultUtil.success("更新成功！");
        } catch (Exception e) {
            //e.printStackTrace();
            log.warn("【权限管理】更新权限时出现错误，错误信息："+e.getMessage());
            return ResultUtil.error("系统错误，错误信息："+ e.getMessage());
        }
    }


    @DeleteMapping("deletePermissionById")
    @OperateLog(value = "根据id删除权限",module = "权限模块")
    public Result<Object> deletePermissionById(Long id){
        try {
            //删除子节点
            List<Permissions> childPermissionList = permissionsService.findByParentId(id);
            if(childPermissionList != null && !childPermissionList.isEmpty()){
                permissionsService.delete(childPermissionList);
            }
            permissionsService.delete(id);
            return ResultUtil.success("删除成功！");
        } catch (Exception e) {
            log.warn("【权限管理】删除权限时出现错误，错误信息："+e.getMessage());
            return ResultUtil.error(e);
        }


    }



    @GetMapping("getPermissionByRoleId")
    public Result<Object> getPermissionByRoleId(@RequestParam(value = "spread",required = false) boolean spread,
                                                @RequestParam(value="check",required = false)boolean check,
                                                @RequestParam(value="roleId",required = false) Long roleId){
        List<LayUITree> layUITrees = null;
        List<Permissions> permissionList = permissionsService.findByLevel(1);
        //角色 可访问的菜单
        if(roleId == null){
            layUITrees = layuiTreeUtils.changePermissionTree(permissionList, true,false);
        }else {
            Role role = roleService.get(roleId);
            List<Permissions> rolePermissions = role.getPermissions();
            layUITrees = layuiTreeUtils.changePermissionTree(permissionList, rolePermissions);
        }
        return ResultUtil.data(layUITrees);
    }

    @PostMapping("updateRolePermission")
    public Result<Object> updateRolePermission(@RequestParam(value="roleId") Long roleId,
                                               @RequestParam(value="checkedPermissions[]",required = false)Integer[] checkedPermissions){

        List<IntermediateEntity> rolePermissions = new ArrayList<>();
        if(checkedPermissions == null){checkedPermissions = new Integer[0];}
        List<Integer> cheackPermissionIdList = Arrays.stream(checkedPermissions).collect(Collectors.toList());
        try {
            //先删除原先的数据。
            int i = roleService.deleteRolePermissionByRoleId(roleId);
            //再插入新数据
            for (Integer menuId : cheackPermissionIdList) {
                IntermediateEntity data = new IntermediateEntity(roleId,menuId.longValue());
                rolePermissions.add(data);
            }
            if(!rolePermissions.isEmpty()){
                roleService.insertRolePermissions(rolePermissions);
            }
            return ResultUtil.success("修改成功,重新登陆后生效！");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.success("修改失败！错误信息:"+e.getMessage());
        }
    }
}
